#include <iostream>
#include <map>
#include <string>
#include <utility>

using std::cout;
using std::endl;
using std::map;
using std::string;
using std::pair;
using std::make_pair;

template <typename Container>
void display(const Container &con)
{
    for(auto &elem : con)
    {
        cout << elem.first << "  " << elem.second << endl;
    }
}

void test()
{
    //map的特征
    //1、存放的是key-value类型，key值是唯一的，不能重复；但是
    //value值是可以重复的
    //2、默认情况下，会按照key值进行升序排列
    map<int, string> number = {
        {1, "beijing"},
        {10, "beijing"},
        pair<int, string>(3, "nanjing"),
        pair<int, string>(6, "wuhan"),
        make_pair(4, "wuhan"),
        make_pair(10, "wuhan"),
        make_pair(7, "hubei"),
    };
    display(number);

    cout << endl << "map查找操作" << endl;
    size_t cnt = number.count(8);
    cout << "cnt = " << cnt << endl;

    /* map<int, string>::iterator it = number.find(7); */
    auto it = number.find(7);
    if(it == number.end())
    {
        cout << "该元素不在map中" << endl;
    }
    else
    {
        cout << "该元素存在map中 " << it->first 
             << "    " << it->second << endl; 
    }

    cout << endl << "insert操作" << endl;
    pair<map<int, string>::iterator, bool> ret 
        /* = number.insert({5, "dongjing"}); */
        /* = number.insert(pair<int, string>(5, "dongjing")); */
        = number.insert(make_pair(5, "dongjing"));
    if(ret.second)
    {
        cout << "插入成功 " << ret.first->first
             << "   " << ret.first->second << endl;
    }
    else
    {
        cout << "插入失败" << endl;
    }
    display(number);

    cout << endl << "map的下标操作" << endl;
    cout << "number[1] = " << number[1] << endl;//查找
    cout << "number[8] = " << number[8] << endl;//插入
    display(number);

    cout << endl;
    //T &operator[](const Key &)
    number[8] = "hainan";//修改
    number[10] = "hainan";
    display(number);

    const map<int, string> mm = {{1, "wuhan"}};
    /* mm[1];//ok */
}

int main(int argc, char *argv[])
{
    test();
    return 0;
}

